/**
 * Created by zhongb on 2017/4/11.
 */
var $ = require('jquery');
require('easyui');
require('fancybox');
var $alert = require('libs/alert');
var $confirm = require("libs/confirm");
var isSale = require('libs/user-type').isSale;
$(function () {
    var mod = (function ($,doc,win) {
        var $doc = $(doc),
            $win = $(win),
            $typeSD = $('.type-sd'),
            $typeSCS = $('.type-scs'),
            $typeSCA = $('.type-sca'),
            $baseInfoSD = $('#baseInfoSD'),
            $baseInfoSCS = $('#baseInfoSCS'),
            $baseInfoSCA = $('#baseInfoSCA'),
            $deliveryInfoSD = $('#deliveryInfoSD'),
            $deliveryInfoSCS = $('#deliveryInfoSCS'),
            $deliveryInfoSCA = $('#deliveryInfoSCA'),
            $table1 = $('#table1'),
            $table2 = $('#table2'),
            $packageFancy = $('#packageFancy'),
            $packageTable = $('#packageTable'),
            $goodsInfo = $('#goodsinfo'),
            $tableAddForm = $('#tableAdd_form');
        var status = {
            draft: '未提交',
            commit: '已提交',
            c_collect: '已揽收',
            c_receive: '已收货',
            c_ourtoom: '集货出库',
            p_inroom: '转运入库',
            p_outroom: '转运出库',
            o_inroom: '海外入库',
            o_shelve: '海外上架',
            cancelled: '报废',
            c_goods_check: '新品检查',
            c_check: '验收',
            c_volume: '称重量体积',
            m_cancel: '已取消'
        };
        var express = {
            "sf": "顺丰",
            "st": "申通",
            "EMS": "EMS",
            "qt": "其他"
        };
        var orderId = $.getUrlParam("id");
        var selfFlag = $.getUrlParam("self");
        var listenerInit = function () {
            $doc.on('click','a[name=packageDetail]',function () {
                if (selfFlag != 'N'){
                    return false;
                }
                var boxId = $(this).data('id');
                $.get('api/v1/p/mms/order/boxGoodsDetail',{boxId:boxId},function (res) {
                    if(res.code == 200){
                        /*$.fancybox.open({
                            type : 'inline',
                            src  : '#packageFancy',
                            transitionEffect  : "fade",
                            afterShow: function () {
                                $('#packageTable').datagrid('loadData',{total:res.data.length,rows:res.data});
                            }
                        });*/

                        $goodsInfo.modal("show");
                        $('tbody',$tableAddForm).empty();
                        $.each(res.data,function (index,obj) {
                            var tr ="<tr>" +
                                "<td>"+obj.goodsCode+"</td>" +
                                "<td>"+obj.goodsName+"</td>" +
                                "<td><input type='text' class='form-control' value='"+obj.num+"' data-id='"+obj.id+"'></td>" +
                                "<td align='middle'><a href='javascript:;' name='modify' data-id='"+obj.id+"'>修改</a></td>" +
                                "</tr>";
                            $('tbody',$tableAddForm).append(tr);
                        });
                    }else{
                        $alert(res.message);
                    }
                });
            });
            $doc.on('click','a[name=modify]',function () {
                var id = $(this).data('id');
                var num = $('tbody tr',$tableAddForm).find("input[data-id="+id+"]").val();
                if (!/^\d+$/.test(num)) {
                    $alert('输入的不是正整数');
                    return false;
                }
                // var index = $('#packageTable').datagrid('getRowIndex', id);
                // var row = $('#packageTable').datagrid('getData').rows[index];
                $confirm("确认修改吗?",function () {
                    $.ajax({
                        url:"api/v1/p/mms/order/updateGoodsDetail",
                        type:"post",
                        data:JSON.stringify({"id":id, "nums":num}),
                        contentType: "application/json; charset=utf-8",
                        dataType:"json",
                        success:function (result) {
                            if(result.code=="200") {
                                $table1.datagrid('reload');
                                $baseInfoSD.find('span').eq(8).text(result.data);
                                $alert("修改成功!");
                            }else{
                                $alert(result.message);
                            }
                        }
                    });
                });

            });
            $doc.on('click','a[name=pkgCancel]',function () {
                var boxId = $(this).data('id');
                $confirm("确认取消该包裹吗？",function () {
                    $.get('api/v1/p/mms/order/boxCancel',{boxId:boxId},function (res) {
                        if(res.code == 200){
                            $table1.datagrid('reload');
                        }else{
                            $alert(res.message);
                        }
                    });
                });
            });
        };
        var table1Init = function () {
            $table1.datagrid({
                url:'api/v1/p/mms/order/orderBoxList',
                border: false,
                pagination: true,
                pageSize: 10,
                pageList: [10, 20, 50, 100],
                singleSelect: true,
                rownumbers: true,
                emptyMsg: '暂无数据',
                queryParams: {
                    orderId: orderId
                },
                columns:[[
                    {
                        field : 'boxCode',
                        title : '包裹码',
                        width : '15%',
                        formatter: function(value,row,index){
                            return "<a href='javascript:;' name='packageDetail' data-id='"+row.id+"'>"+value+"</a>"
                        }
                    },{
                        field : 'skuNums',
                        title : 'SKU数量',
                        width : '9%'
                    },{
                        field : 'goodsNum',
                        title : '预报商品数量',
                        width : '9%'
                    },{
                        field : 'shelveNum',
                        title : '上架商品数量',
                        width : '9%'
                    },{
                        field : 'regSize',
                        title : '预报 长x宽x高(cm) | 重量(kg)',
                        width : '20%',
                        formatter: function(value,row,index){
                            if("" == row.regLength || "" == row.regWidth || "" == row.regHeight || "" == row.regWeight){
                                return "";
                            }
                            return row.regLength+"X"+row.regWidth+"X"+row.regHeight+" | "+ row.regWeight;
                        }
                    },{
                        field : 'factSize',
                        title : '实际 长x宽x高(cm) | 重量(kg)',
                        width : '20%',
                        formatter: function(value,row,index){
                            if("" == row.factLength || "" == row.factWidth || "" == row.factHeight || "" == row.factWeight){
                                return "";
                            }
                            return row.factLength+"X"+row.factWidth+"X"+row.factHeight+" | "+ row.factWeight;
                        }
                    },{
                        field : 'tranStatus',
                        title : '状态',
                        width : '8%',
                        formatter: function(value,row,index){
                            return status[value];
                        }
                    },{
                        field : 'opt',
                        title : '操作',
                        hidden:isSale,
                        width : '10%',
                        formatter: function(value,row,index){
                            if($.inArray(row.tranStatus,["o_inroom","o_shelve","cancelled","m_cancel","p_outroom","c_ourtoom",""]) === -1){
                                return "<a href='javascript:;' name='pkgCancel' data-id='"+row.id+"'>取消</a>";
                            }else{
                                return "";
                            }
                        }
                    }
                ]],
                onClickRow: function (rowIndex, rowData) {
                    $(this).datagrid('unselectRow', rowIndex);
                },
                loadFilter:function(data){
                    if(data.code == '200'){
                        return data.data;
                    }else{
                        return [];
                    }
                }
            });
        };
        var table2Init = function () {
            $table2.datagrid({
                data: [],
                border : false,
                rownumbers: true,
                nowrap: false,
                columns:[[
                    {
                        field : 'spec',
                        title : '集装箱规格',
                        width : '25%'
                    },{
                        field : 'code',
                        title : '集装箱号',
                        width : '25%'
                    },{
                        field : 'secretKey',
                        title : '集装箱密码',
                        width : '25%'
                    },{
                        field : 'isFlooringLoad',
                        title : '是否打板',
                        width : '25%',
                        formatter: function(value,row,index){
                            switch (value){
                                case '0': return '打板';
                                case '1': return '不打板';
                                default: return '';
                            }
                        }
                    }
                ]],
                onClickRow: function (rowIndex, rowData) {
                    $(this).datagrid('unselectRow', rowIndex);
                }
            });
        };
        var actionSD = function (data) {
            $typeSD.show();
            $baseInfoSD.setForm({
                orderNo: data.orderNo,
                entName: data.entName,
                collectWarehouseName: data.collectWarehouseName,
                toWarehouseName: data.toWarehouseName,
                logisticsName: data.logisticsName,
                logisticsPlanName: data.logisticsPlanName,
                tNums: data.tNums,
                skuNums: data.skuNums,
                tGoodsNums: data.tGoodsNums,
                tWeight: data.tWeight,
                tVolumn: data.tVolumn
            });
            $deliveryInfoSD.setForm({
                expressProviderName: express[data.expressProviderName],
                expressNo: data.expressNo
            });
            table1Init();
        };
        var actionSCS = function (data) {
            $typeSCS.show();
            $baseInfoSCS.setForm({
                orderNo: data.orderNo,
                entName: data.entName,
                toWarehouseName: data.toWarehouseName,
                logisticsName: data.logisticsName,
                tNums: data.tNums,
                skuNums: data.skuNums,
                tGoodsNums: data.tGoodsNums,
                tWeight: data.tWeight,
                tVolumn: data.tVolumn
            });
            $deliveryInfoSCS.setForm({
                expectedToOwmsTime: data.expectedToOwmsTime
            });
            table1Init();
            table2Init();
            $.post('api/v1/p/mms/order/loadContainers',{orderId: orderId},function (res) {
                if(res.code == 200){
                    $table2.datagrid('loadData',{
                        total: res.data.length,
                        rows: res.data
                    });
                } else {
                    $alert(res.message);
                }
            })
        };
        var actionSCA = function (data) {
            $typeSCA.show();
            $baseInfoSCA.setForm({
                orderNo: data.orderNo,
                entName: data.entName,
                toWarehouseName: data.toWarehouseName,
                logisticsName: data.logisticsName,
                tNums: data.tNums,
                skuNums: data.skuNums,
                tGoodsNums: data.tGoodsNums,
                tWeight: data.tWeight,
                tVolumn: data.tVolumn
            });
            $deliveryInfoSCA.setForm({
                internationalLogisticsCarrier: data.internationalLogisticsCarrier,
                internationalLogisticsNo: data.internationalLogisticsNo,
                expectedToOwmsTime: data.expectedToOwmsTime
            });
            table1Init();
        };
        var dataRender = function (type) {
            if(type === 'SD'||!type){
                return actionSD;
            }else if(type === 'SCS'){
                return actionSCS;
            }else if(type === 'SCA'){
                return actionSCA;
            }
        };
        listenerInit();
        $.get('api/v1/p/mms/order/load',{id: orderId},function (res) {
            if(res.code == 200){
                dataRender(res.data.orderType)(res.data);
            }else{
                $alert(res.message);
            }
        });
    })($,document,window);
    /*function tableInit(orderId) {
        $('#packageTable').datagrid({
            border : false,
            data: [],
            rownumbers:true,
            emptyMsg: '暂无数据',
            columns:[[
                {
                    field:'goodsCode',
                    title:'商品编码',
                    width:240
                },{
                    field:'goodsName',
                    title:'商品名称',
                    width:240
                },
                {
                    field:'num',
                    title:'商品数量',
                    width:210
                }
            ]]
        });

    }*/
});
